import type {
  LocationQuery,
  LocationQueryRaw,
  RouteLocationRaw,
  RouteParams,
  RouteRecordName
} from 'vue-router'

import { RouterName } from './name'

type RedirectQuery = LocationQueryRaw & {
  _params: string
  _redirect: string
}

type Route = {
  name?: RouteRecordName | null
  query: LocationQuery
  params: RouteParams
}

export function buildRedirectLoginLocation({ name, query, params }: Route): RouteLocationRaw {
  return {
    name: RouterName.Login,
    query: {
      _redirect: name?.toString() ?? RouterName.Home,
      _params: (params && JSON.stringify(params)) || '',
      ...query
    } satisfies RedirectQuery
  }
}

export function parseRollbackLocation({ query }: Route): RouteLocationRaw {
  const { _redirect, _params, ...rest } = query as RedirectQuery
  return {
    name: _redirect ?? RouterName.Home,
    params: _params && JSON.parse(_params as string),
    query: rest
  }
}
